<script setup lang='ts'>
import { layoutSourceSave, layoutSourceUpdate, useApplicationList } from '@fl/api/advertising-api'
import { SubmitBtn } from '@fl/components'
// import { TABLE1, TABLE2 } from '../../hooks/constant'
import type { appType, reqjsonType, tagType } from '../../../advertising-management/type'
import { tabValue } from '../../../advertising-management/type'
import materialModule from '../../../advertising-management/components/material-module.vue'

const props = defineProps<{
    total: number
}>()
const emits = defineEmits(['refresh'])
const { total } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })
const editId = defineModel<number>('id', { required: false })
const editAppListId = defineModel<number | string>('appListId', { required: false }) // 编辑时的应用id
const state = defineModel<any>('adForm', { required: true })
console.log('state', state.value, 'editId', editId.value)

const tempForwardParams = ref<string>('') // 临时存储forwardParams

const reqjson = ref<any>([])
const btnLoading = ref<boolean>(false)
const dialogVisible = ref<boolean>(false) // 选择素材组件
const selectType = ref<string>('') // imgUri图片 headIconUri头角标 footIconUri尾巴角标
const fileType = ref<number>(tabValue.PIC_MANAGE)
const tabsList: tagType[] = [
    {
        label: '图片管理',
        value: tabValue.PIC_MANAGE,
    },
    // {
    //     label: '视频管理',
    //     value: tabValue.VIDEO_MANAGE,
    // },
]

const formRef = ref()
const title = ref('添加')

const appList = ref<any>([])

// 关联应用
const { data: appRes, isLoading } = useApplicationList(visible)
watchEffect(() => {
    if (appRes.value) {
        appList.value = appRes.value
    }
    if (editAppListId.value) {
        console.log('editAppListId', editAppListId.value)
        changeAppList(editAppListId.value)
    }
    title.value = editAppListId.value ? '编辑' : '添加'
})

// 设置应用类型
function changeAppList(val) {
    console.log('changeAppList', val)
    const currentApp: appType = appList.value.find((item: appType) => item.id === val)
    if (currentApp && currentApp.reqjson) {
        reqjson.value = JSON.parse(currentApp.reqjson)
        console.log('reqjson', reqjson.value)
        if (state.value.forwardParams) {
            tempForwardParams.value = state.value.forwardParams
            const forwardParams = JSON.parse(state.value.forwardParams)
            for (const key in forwardParams) {
                state.value[key] = forwardParams[key]
            }
        }
    }
    else {
        reqjson.value = []
        const forwardParams = JSON.parse(tempForwardParams.value || '{}')
        for (const key in forwardParams) {
            delete state.value[forwardParams[key]] // 清除之前的forwardParams
        }
        tempForwardParams.value = ''
        console.log('没有reqjson', state.value)
    }
}

// 打开素材组件
function setMaterial(type) {
    console.log('setMaterial', type)
    selectType.value = type
    dialogVisible.value = true
    reqjson.value = []
}

// 删除素材
function delMaterial(type) {
    state.value[type] = ''
}

// 勾选素材
function selectMaterial(url) {
    state.value[selectType.value] = url
}

// 提交选择素材
function advertisingSbumit() {
    dialogVisible.value = false
}

// 弹窗关闭前
function beforeClose() {
    // state.value[selectType.value] = ''
    dialogVisible.value = false
    // selectType.value = ''
}

// 提交广告
async function submit(formEl) {
    // const valid = await formRef.value.formInstance.validate()
    const valid = await formEl.validate()
    if (valid) {
        if (valid) {
            let msg = ''
            const { activeEnd, activeStart, appListId, footIconUri, groupSnapshotId, headIconUri, id, imgUri, sort, title } = state.value
            const params = {
                activeEnd,
                activeStart,
                appListId,
                footIconUri,
                forwardParams: '',
                groupSnapshotId,
                headIconUri,
                id: editId.value,
                imgUri,
                sort: sort ?? total.value + 1,
                title,
            }
            if (reqjson.value.length) {
                const result = await reqjson.value.reduce((prev, cur: reqjsonType) => {
                    if (state.value[cur.value]) {
                        prev[cur.value] = state.value[cur.value]
                    }
                    else {
                        prev[cur.value] = '$'
                    }
                    return prev
                }, {})
                params.forwardParams = JSON.stringify(result)
            }
            if (editId.value) {
                btnLoading.value = true
                await layoutSourceUpdate(params).then(() => {
                    msg = '编辑成功'
                }).catch(() => {
                    btnLoading.value = false
                })
            }
            else {
                btnLoading.value = true
                await layoutSourceSave(params).then(() => {
                    msg = '添加成功'
                }).catch(() => {
                    btnLoading.value = false
                })
            }
            if (msg) {
                ElMessage({
                    message: msg,
                    type: 'success',
                })
                emits('refresh', groupSnapshotId)
                cancel()
            }
            btnLoading.value = false
        }
        else {
            console.log('error submit!')
        }
    }
}

function cancel() {
    editId.value = undefined
    visible.value = false
    reqjson.value = [] // 重置参数栏
}

function reset() {
    editAppListId.value = undefined
    editId.value = undefined
    formRef.value?.resetFields()
}

defineExpose({
    reset,
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                :has-footer="false"
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="mt20">
                <el-form ref="formRef"
                         :model="state"
                         label-width="100"
                         label-position="right"
                >
                    <el-form-item label="名称："
                                  prop="title"
                                  :rules="{
                                      required: true,
                                      message: '请输入',
                                      trigger: 'blur',
                                  }"
                    >
                        <el-input v-model="state.title" />
                    </el-form-item>

                    <el-form-item label="图片："
                                  prop="imgUri"
                                  :rules="{
                                      required: true,
                                      message: '请输入',
                                      trigger: 'change',
                                  }"
                    >
                        <div v-if="state.imgUri"
                             class="adImg-box"
                             @click="delMaterial('imgUri')"
                        >
                            <img :src="state.imgUri"
                                 width="108"
                                 alt="图片"
                            >

                            <el-icon class="material-img-icon hidden">
                                <Delete />
                            </el-icon>
                        </div>

                        <div class="material-img"
                             @click="setMaterial('imgUri')"
                        >
                            <el-icon class="material-img-icon">
                                <Plus />
                            </el-icon>
                        </div>
                    </el-form-item>

                    <el-form-item label="头角标：">
                        <div v-if="state.headIconUri"
                             class="adImg-box"
                             @click="delMaterial('headIconUri')"
                        >
                            <img :src="state.headIconUri"
                                 width="108"
                                 alt="头角标"
                            >

                            <el-icon class="material-img-icon hidden">
                                <Delete />
                            </el-icon>
                        </div>

                        <div class="material-img"
                             @click="setMaterial('headIconUri')"
                        >
                            <el-icon class="material-img-icon">
                                <Plus />
                            </el-icon>
                        </div>
                    </el-form-item>

                    <el-form-item label="尾角标：">
                        <div v-if="state.footIconUri"
                             class="adImg-box"
                             @click="delMaterial('footIconUri')"
                        >
                            <img :src="state.footIconUri"
                                 width="108"
                                 alt="尾角标"
                            >

                            <el-icon class="material-img-icon hidden">
                                <Delete />
                            </el-icon>
                        </div>

                        <div class="material-img"
                             @click="setMaterial('footIconUri')"
                        >
                            <el-icon class="material-img-icon">
                                <Plus />
                            </el-icon>
                        </div>
                    </el-form-item>

                    <el-form-item label="关联应用："
                                  prop="appListId"
                                  :rules="{
                                      required: true,
                                      message: '请选择',
                                      trigger: 'change',
                                  }"
                    >
                        <el-select v-model="state.appListId"
                                   filterable
                                   clearable
                                   @change="changeAppList"
                        >
                            <el-option v-for="appItem in appList"
                                       :key="appItem.id"
                                       :label="appItem.appName"
                                       :value="appItem.id"
                            />
                        </el-select>
                    </el-form-item>

                    <template v-if="reqjson.length">
                        <span v-for="itemJson in reqjson"
                              :key="itemJson.value"
                        >
                            <el-form-item v-if="itemJson?.isShow"
                                          :prop="itemJson.value"
                                          :rules="{ required: true, message: '请输入', trigger: 'blur' }"
                            >
                                <template #label>
                                    <a :title="itemJson.title"
                                       class="json-label"
                                    >{{ `${itemJson.title}：` }}</a>
                                </template>

                                <el-input v-model="state[itemJson.value]" />
                            </el-form-item>
                        </span>
                    </template>
                </el-form>
            </div>

            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="btnLoading"
                           @click="submit(formRef)"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>

    <el-dialog v-model="dialogVisible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               title="选择素材"
               class="material-select-dialog"
               width="1280"
               :before-close="beforeClose"
    >
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary"
                           :loading="btnLoading"
                           @click="advertisingSbumit()"
                >
                    提交
                </el-button>
            </div>
        </template>
        <!-- 选择素材：这个v-if不加会影响素材组件的刷新 -->
        <template v-if="dialogVisible">
            <el-tabs v-model="fileType"
                     class="material-type-tabs"
            >
                <el-tab-pane v-for="tabItem in tabsList"
                             :key="tabItem.value"
                             :label="tabItem.label"
                             :name="tabItem.value"
                >
                    <material-module v-if="fileType === tabItem.value"
                                     v-model="tabItem.value"
                                     :select-type="selectType"
                                     @checked="selectMaterial"
                    />
                </el-tab-pane>
            </el-tabs>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.material-select-dialog {
    height: 88% !important;

    .el-dialog__body {
        height: 80%;
        overflow-y: auto;
    }
}

.material-img {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.material-img:hover {
    border-color: var(--el-color-primary);
}

.el-icon.material-img-icon {
    font-size: 28px;
    color: #8c939d;
    width: 108px;
    height: 108px;
    text-align: center;
}

.adImg-box {
    width: 108px;
    height: 108px;
    display: flex;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-right: 12px;
    .hidden {
        display: none;
        position: absolute;
        z-index: 10;
        cursor: pointer;
        width: 108px;
        height: 108px;
        align-items: center;
    }
    &:hover {
        .hidden {
            display: flex;
        }
    }
}
.json-label {
    display: block;
    width: 100px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    text-align: right;
}
</style>
